//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~ Timer32 ~~ By Jesus4Lyf ~~
//~~ NOVA Version, revised by Conquest-NOVA~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

library T32n
    globals
        private constant real T32_PERIOD=0.03125
        private integer N = 0
        private trigger X = CreateTrigger()
        private timer T32 = CreateTimer()
    endglobals
    
    function GetGameTick takes nothing returns real
        return T32_PERIOD
    endfunction
    
    function GetT32ThreadCount takes nothing returns integer
        return N
    endfunction
    
    private function O takes nothing returns nothing
        call TriggerEvaluate(X)
    endfunction
    

    module T32n
        private thistype next
        private thistype prev
        private boolean runningPeriodic     = false
        private static boolean registered   = false
        
        private static method T takes nothing returns boolean
            local thistype a=thistype(0).next
            loop
                exitwhen a==0
                call a.tick()
                set a=a.next
            endloop
            return false
        endmethod
        
        method start takes nothing returns nothing
        
            if( .registered == false) then
                set .registered = true
                call TriggerAddCondition(X,Condition(function thistype.T))
            endif
            if not this.runningPeriodic then
                set thistype(0).next.prev=this
                set this.next=thistype(0).next
                set thistype(0).next=this
                set this.prev=thistype(0)
                
                set this.runningPeriodic=true
                if( N == 0) then
                    call TimerStart(T32,T32_PERIOD,true,function O)
                endif
                set N = N + 1
            endif
        endmethod
        
        method stop takes nothing returns nothing
            if this.runningPeriodic then
               
                set N = N - 1
                if( N <= 0) then
                    call PauseTimer(T32)
                    set N = 0
                endif
                 // This is some real magic.
                set this.prev.next=this.next
                set this.next.prev=this.prev
                // This will even work for the starting element.
                
                set this.runningPeriodic=false     
            endif
        endmethod
    endmodule

    
endlibrary